﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Text;
using System.Text.Json;
using Egg;
using System.Reflection;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Ref_PostgresEFCore
{
    class Program
    {
        // 输出应答结果
        static void Output(JsonResponse response)
        {
            var json = JsonSerializer.Serialize(response, response.GetType());
            Console.WriteLine(json);
        }

        // 输出应答结果
        static void Output()
        {
            Output(new JsonResponse());
        }

        // 输出应答结果
        static void Output(string message)
        {
            Output(new JsonResponse() { Message = message });
        }

        // 主线程
        static async Task MainProcess(string[] args)
        {
            await Task.Delay(1);

            // 获取参数
            var arg = egg.Assembly.CreateArguments<Egg.Arguments.EArguments>(args);

            // 获取路径
            if (!arg.ContainsKey("path")) throw new FriendlyException($"path is not found.");
            string filePath = arg["path"];
            Debug.WriteLine($"[Path] {filePath}");

            // 加载Dll
            var ass = Assembly.LoadFrom(filePath);
            var tps = ass.GetTypes();
            var response = new JsonResponse<List<TableInfo>>();
            response.Result = new List<TableInfo>();
            foreach (var tp in tps)
            {
                var table = tp.GetCustomAttribute<TableAttribute>();
                if (table != null)
                {
                    try
                    {
                        Debug.WriteLine($"[Class] {tp.FullName}");
                        var tableDescription = tp.GetCustomAttribute<DescriptionAttribute>();
                        // 加载表信息
                        TableInfo info = new TableInfo()
                        {
                            TableName = table.Name,
                            TableAbbr = tp.Name.GetAbbr(),
                            TableSchema = table.Schema,
                            TableClassNamespace = tp.Namespace,
                            TableClassName = tp.Name,
                            TableInherit = tp.BaseType?.Name,
                            TableDescription = tableDescription is null ? "" : tableDescription.Description,
                            Columns = new List<ColumnInfo>(),
                        };
                        if (info.TableName.IsEmpty()) info.TableName = tp.Name.GetUnderScoreCase();
                        if (info.TableDescription.IsEmpty()) info.TableDescription = tp.Name;
                        // 加载字段信息
                        var pros = tp.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                        for (int i = 0; i < pros.Length; i++)
                        {
                            var pro = pros[i];
                            var columnNotForeignKey = pro.GetCustomAttribute<ForeignKeyAttribute>() is null;
                            // 过滤外键
                            if (columnNotForeignKey)
                            {
                                var column = pro.GetCustomAttribute<ColumnAttribute>();
                                var columnDescription = pro.GetCustomAttribute<DescriptionAttribute>();
                                var columnKey = pro.GetCustomAttribute<KeyAttribute>();

                                var columnProType = pro.PropertyType.Name;
                                var columnProTypeName = pro.PropertyType.FullName;
                                var columnNullable = false;
                                if (columnProType == "Nullable`1")
                                {
                                    if (pro.PropertyType.Namespace == "System")
                                    {
                                        columnProTypeName = pro.PropertyType.GetGenericArguments()[0].FullName;
                                        columnNullable = true;
                                    }
                                }
                                // 加载表信息
                                ColumnInfo columnInfo = new ColumnInfo()
                                {
                                    ColumnDescription = columnDescription is null ? "" : columnDescription.Description,
                                    ColumnName = column is null ? "" : column.Name,
                                    ColumnNullable = columnNullable,
                                    ColumnPrimaryKey = columnKey != null,
                                    ColumnPropertyName = pro.Name,
                                    ColumnPropertyType = columnProTypeName,
                                    ColumnRequired = false,
                                    ColumnType = column is null ? "" : column.TypeName,
                                    ColumnTypeLength = 0,
                                    ColumnTypeFloat = 0,
                                };
                                if (columnInfo.ColumnName.IsEmpty()) columnInfo.ColumnName = pro.Name.GetUnderScoreCase();
                                if (columnInfo.ColumnType.IsEmpty()) columnInfo.ColumnType = PostgresHelper.GetPostgresTypeFromType(columnProTypeName);
                                if (columnInfo.ColumnDescription.IsEmpty()) columnInfo.ColumnDescription = pro.Name;
                                info.Columns.Add(columnInfo);
                            }
                        }
                        response.Result.Add(info);
                    }
                    catch { }
                }
            }
            Output(response);
        }

        static void Main(string[] args)
        {
            try
            {
                MainProcess(args).Wait();
            }
            catch (FriendlyException ex)
            {
                // 测试输出
                Output(new JsonResponse()
                {
                    IsSuccessed = false,
                    Message = ex.Message,
                });
            }
            catch (Exception ex)
            {
                // 测试输出
                Output(new JsonResponse()
                {
                    IsSuccessed = false,
                    Message = "运行发生错误",
                    Error = new JsonResponseError() { Code = 0, Info = ex.ToString() }
                });
            }

        }
    }
}
